<template>
  <div class="page-container">
    <!-- 快捷操作 -->
    <list-quick-navigation ref="listQuickNavigationRef" @change="quickNavigationChange" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="searchFormFn" @reset="onResize" />
    <table-index :table="table" @loadData="loadData">
      <template #carInfo="{ record }">
        {{ (record.licenseNo || '-') + '/' + (record.modelName || '-') + '/' + (record.vin || '-') }}</template
      >
      <template #hrhcSyncStatusName="{ record }">
        <!-- 标签 -->
        <div style="display: flex; justify-content: flex-start; align-items: center">
          {{ record.hrhcSyncStatusName || '-' }}
          <a-tag :color="getTagColor(record.etcSourceName)" v-if="record.etcSourceName" style="margin-left: 6px">{{
            record.etcSourceName
          }}</a-tag>
          <a-popover trigger="click" v-if="record.hrhcSyncStatus == 20">
            <a-button class="case-btn" type="outline">原因</a-button>
            <template #content>
              <p>{{ '失败原因：' + record.synchronizationFailReason }}</p>
            </template>
          </a-popover>
        </div>
      </template>
      <template #table-summary v-if="queryParam.hrhcSyncStatusList[0] == 20">
        <span style="padding-left: 20px">原因汇总：1、有必填项还未填写 2、备案审核未通过</span>
      </template>
    </table-index>
    <!-- 修改 -->
    <car-info-edit-modal ref="editModal" @ok="initData" />
    <!-- 批量修改 -->
    <car-info-batch-modal ref="batchModal" @ok="initData" />
    <!-- 提交同步/一键提交同步 -->
    <service-modal ref="serviceModalRef" @ok="initData" />
  </div>
</template>

<script setup name="CarInfoList">
  import { ref, reactive, onMounted, computed } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { getHrhcList, getHrhcBatchSubmitSync, getHrhcSubmitSync, getHrhcReFilings } from '@/api/asset/equipment'
  import listQuickNavigation from './components/list-quick-navigation.vue'
  import carInfoEditModal from './form/index.vue'
  import carInfoBatchModal from './form/batch-modal.vue'
  import serviceModal from './form/service-modal.vue'
  import { Message } from '@arco-design/web-vue'
  import { Modal } from '@arco-design/web-vue'
  import { useRoute } from 'vue-router'
  import { getHrhcStatistics } from '@/api/asset/equipment'
  import { usePageDict } from '@/hooks/useDict'

  import useNavigate from '@/hooks/useNavigate'
  const { navigateTo } = useNavigate()

  const route = useRoute()

  const listQuickNavigationRef = ref()
  const editModal = ref(null)
  const batchModal = ref(null)
  const serviceModalRef = ref(null)
  const queryParam = reactive({
    hrhcSyncStatusList: [],
  })
  const config = ref({})

  // 读取商户配置
  import useUserStore from '@/store/modules/user'
  const userStore = useUserStore()
  userStore.setEpDetail((result) => {
    console.log('result', result)
    config.value = {
      hrhcEtcEnabled: result.hrhcEtcEnabled || '',
      tboxEnabled: result.tboxEnabled || '',
      quantumEtcEnabled: result.quantumEtcEnabled || '',
    }
  })

  const carSyncHrhcDict = usePageDict('carSyncHrhcDict')

  // 查询条件
  const searchList = computed(() => {
    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input' },
      { label: '车架号', prop: 'vinLike', placeholder: '请输入', type: 'a-input' },
      {
        label: '车型',
        prop: 'modelId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenantList',
        },
      },
      {
        label: '归属门店',
        prop: 'siteId',
        type: 'remote-select',
        attrs: {
          type: 'site_listBystaff',
        },
      },
      {
        label: 'ETC服务商',
        prop: 'etcSource',
        type: 'a-select',
        options: carSyncHrhcDict.etcSourceEnums,
      },
    ]
  })

  // 快捷导航点击事件
  const quickNavigationChange = (param) => {
    // 清空
    // for (var k in queryParam) {
    //   queryParam[k] = undefined
    // }
    // 更新数据
    let newParam = {
      ...param,
    }
    for (var k in newParam) {
      queryParam[k] = newParam[k]
    }
    loadData(1, 'quickNavigation')
  }
  // NO_SYNC(0, "未发起同步"),
  // SYNCING(10, "同步中"),
  // WAIT_MODIFY(20, "待修改"),
  // FILING(30, "备案中"),
  // SYNC_PASS(40, "已通过"),
  const operates = computed(() => {
    return [
      {
        label: '操作记录',
        // 车辆同步状态是“备案中、已通过”的数据，
        // 车辆同步状态是“待修改”的数据，
        // 车辆同步状态是“进行中”的数据
        permission: 'svms:asstes:equipment:car-info.operaterecords',
        show: (record) =>
          record.hrhcSyncStatus == 30 || record.hrhcSyncStatus == 40 || record.hrhcSyncStatus == 20 || record.hrhcSyncStatus == 10,
        method: (record) => {
          navigateTo('/equipment/car-info/operate-records/' + record.id, `${record.licenseNo}-的操作记录`)
        },
      },
      {
        label: '重新备案',
        // 仅限于etc业务开启时，针对车辆同步状态为“已通过”的车，能进行操作
        permission: 'svms:asstes:equipment:car-info.filing',
        show: (record) => record.hrhcSyncStatus == 40 && config.value.hrhcEtcEnabled,
        method: (record) => {
          Modal.confirm({
            title: '提示',
            simple: true,
            cancelText: '取消',
            okText: '确认',
            bodyStyle: {
              'text-align': 'center',
            },
            content: '该车可以修改信息并重新提交备案了',
            onOk: () => {
              getHrhcReFilings({ id: record.id }).then((res) => {
                Message.success(res.message)
                // 确认提示之后，自动切换sheet到“待修改”中，并将这台车的信息修改页调出。
                editModal.value.show(record.id, config.value, 'single')
                listQuickNavigationRef.value.clickActive({ label: '待修改', prop: 'waitModifyCount' })
              })
            },
          })
        },
      },
      {
        label: '提交同步',
        // “车辆同步状态”是“待同步”
        permission: 'svms:asstes:equipment:car-info.submit',
        show: (record) => record.hrhcSyncStatus == 0 && (config.value.hrhcEtcEnabled || config.value.quantumEtcEnabled),
        method: (record) => {
          // a. 如果ETC服务商只开通一家，则功能流程同线上，弹出二次确认即可
          // b. 如果ETC服务商开通两家，则点击提交同步按钮时，弹出ETC服务商选择弹框
          if (config.value.hrhcEtcEnabled && config.value.quantumEtcEnabled) {
            serviceModalRef.value.show(record, 'single')
          } else {
            Modal.confirm({
              title: '提示',
              simple: true,
              cancelText: '取消',
              okText: '确认',
              bodyStyle: {
                'text-align': 'center',
              },
              content: '是否确定提交同步',
              onOk: () => {
                getHrhcSubmitSync({ id: record.id, etcSource: config.value.hrhcEtcEnabled ? 1 : 2 }).then((res) => {
                  Message.success(res.message)
                  initData()
                })
              },
            })
          }
        },
      },
      {
        label: '修改',
        // “车辆同步状态”是“待修改”的数据
        permission: 'svms:asstes:equipment:car-info.edit',
        show: (record) => record.hrhcSyncStatus == 20 && (config.value.hrhcEtcEnabled || config.value.quantumEtcEnabled),
        method: (record) => {
          editModal.value.show(record.id, config.value, 'single')
        },
      },
    ]
  })

  const buttons = computed(() => {
    return [
      {
        type: 'primary',
        show: () => {
          return queryParam.hrhcSyncStatusList[0] == 0
        },
        permission: 'svms:asstes:equipment:car-info.batch-submit',
        label: '一键全部提交',
        method: () => {
          // 如果ETC服务商只开通一家，则弹出二次确认，文案：“是否确认批量提交{XXXX}条进行同步”（目前线上没有二次确认，本期新增的）
          // 如果ETC服务商开通两家，则点击提交同步按钮时，弹出ETC服务商选择弹框
          if (config.value.hrhcEtcEnabled && config.value.quantumEtcEnabled) {
            serviceModalRef.value.show('', 'batch')
          } else {
            getHrhcStatistics().then(({ result }) => {
              if (result) {
                Modal.confirm({
                  title: '提示',
                  simple: true,
                  cancelText: '取消',
                  okText: '确认',
                  bodyStyle: {
                    'text-align': 'center',
                  },
                  content: `是否确认批量提交${result.unSyncCount}条进行同步`,
                  onOk: () => {
                    handleSubmit()
                  },
                })
              }
            })
          }
        },
      },
      {
        type: 'primary',
        show: () => {
          return queryParam.hrhcSyncStatusList[0] == 20
        },
        permission: 'svms:asstes:equipment:car-info.batch-edit',
        label: '批量修改',
        method: () => {
          if (config.value.hrhcEtcEnabled || config.value.quantumEtcEnabled) {
            // ETC
            editModal.value.show('', config.value, 'batch')
          } else {
            // TBOX
            batchModal.value.show()
          }
        },
      },
    ]
  })
  // table 配置
  const table = useTable({
    columns: [
      { title: '车辆信息', dataIndex: 'carInfo', slotName: 'carInfo' },
      { title: '归属门店', dataIndex: 'siteName', width: 150 },
      { title: '车辆同步状态', dataIndex: 'hrhcSyncStatusName', slotName: 'hrhcSyncStatusName', width: 200 },
    ],
    tableLoading: false,
    operates: operates.value,
    buttons: buttons.value,
  })

  // 列表接口调用
  const loadData = (page, type) => {
    if (type != 'quickNavigation') {
      listQuickNavigationRef.value.reset()
    }
    const fn = useFetchTableDataApi(table, queryParam, getHrhcList)
    fn(page)
  }

  // 重置
  const onResize = () => {
    queryParam.hrhcSyncStatusList = []
  }

  // 一键全部提交
  const handleSubmit = () => {
    // 一键全部提交按钮：点击后，列表中的所有数据，都将被“提交同步”
    const fn = getHrhcBatchSubmitSync
    fn({ etcSource: config.value.hrhcEtcEnabled ? 1 : 2 }).then(() => {
      Message.success('提交同步成功')
      initData()
    })
  }

  // 操作后的初始化
  const initData = () => {
    loadData(1, 'quickNavigation')
    listQuickNavigationRef.value.getStNum()
  }

  const searchFormFn = () => {
    listQuickNavigationRef.value.clickActive({ label: '总计', prop: 'totalCount' })
  }

  // 根据标签内容返回不同的颜色值
  const getTagColor = (label) => {
    const tagColors = {
      好人好车: 'orange',
      量子: 'arcoblue',
    }
    console.log('tagColors[label]', tagColors[label])

    return tagColors[label] || 'blue'
  }

  onMounted(() => {
    if ('prop' in route.query) {
      let quickObj = listQuickNavigationRef.value.quickNavigationList.find((item) => item.prop == route.query.prop)
      quickObj && listQuickNavigationRef.value.clickActive({ label: quickObj.label, prop: quickObj.prop })
    } else {
      loadData()
    }
  })
</script>

<style lang="less" scoped>
  .case-btn {
    width: 40px;
    height: 20px;
    font-size: 12px;
    margin-left: 8px;
  }
</style>
